
package network;

import model.Product;
import service.ProductSorters;
import model.User;
import java.io.*;
import java.net.Socket;
import java.util.*;
import java.util.Comparator;
import java.util.List;
import java.text.SimpleDateFormat;
/**
 * 商城网络客户端
 * 通过Socket连接服务器获取数据
 * 重构完成：移除ProductService，使用Socket通信
 */
public class EStoreClient {

    // 服务器配置 - 符合任务要求：添加服务器地址和端口号作为成员变量
    private static final String SERVER_HOST = "localhost";
    private static final int SERVER_PORT = 8888;

    private final Scanner scanner = new Scanner(System.in);
    private String sessionId = null;
    private String currentUserRole = "guest";
    private boolean isLoggedIn = false;
    private String username;

    // 移除本地的 shoppingCart，完全使用服务器端购物车
    // private final Map<String, Integer> shoppingCart = new HashMap<>(); // 删除这行

    public EStoreClient() {
        // 使用默认的服务器配置
    }

    public EStoreClient(String serverAddress, int serverPort) {
        // 这个构造函数可以用于自定义服务器地址和端口
    }

    public void start() {
        System.out.println("=== 商城客户端启动 ===");
        System.out.println("正在连接服务器...");

        try {
            while (true) {
                if (!isLoggedIn) {
                    showGuestMenu();
                    int choice = getIntInput("请选择操作：");
                    handleGuestMenu(choice);
                    if (choice == 5) {
                        break;
                    }
                } else {
                    showUserMenu();
                    int choice = getIntInput("请选择操作：");
                    handleUserMenu(choice);
                    if (choice == 0) {
                        continue;
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("程序出现异常: " + e.getMessage());
            e.printStackTrace();
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
    }

    /**
     * 获取整数输入
     */
    private int getIntInput(String prompt) {
        while (true) {
            System.out.print(prompt);
            String input = scanner.nextLine().trim();

            if (input.isEmpty()) {
                System.out.println("请输入有效的数字选项！");
                continue;
            }

            if (!input.matches("\\d+")) {
                System.out.println("请输入有效的数字选项！");
                continue;
            }

            return Integer.parseInt(input);
        }
    }

    /**
     * 显示游客菜单（未登录用户）
     */
    private void showGuestMenu() {
        System.out.println("\n=== 欢迎来到商城（游客模式）===");
        System.out.println("1. 浏览所有商品");
        System.out.println("2. 自定义排序浏览商品");
        System.out.println("3. 登录");
        System.out.println("4. 注册");
        System.out.println("5. 退出");
    }

    /**
     * 处理游客菜单选择
     */
    private void handleGuestMenu(int choice) {
        switch (choice) {
            case 1:
                browseProducts(null);
                break;
            case 2:
                showSortedProducts();
                break;
            case 3:
                login();
                break;
            case 4:
                register();
                break;
            case 5:
                exit();
                break;
            default:
                System.out.println("无效的选项，请重新输入！");
        }
    }



    /**
     * 显示用户菜单（已登录用户）
     */
    private void showUserMenu() {
        if ("admin".equals(currentUserRole)) {
            // 管理员菜单
            System.out.println("\n=== 管理员控制面板 ===");
            System.out.println("当前用户: " + username + " (管理员)");
            System.out.println("1. 浏览所有商品");
            System.out.println("2. 添加新商品");
            System.out.println("3. 修改商品信息");
            System.out.println("4. 删除商品");
            System.out.println("5. 查看所有用户");
            System.out.println("6. 删除用户");
            System.out.println("7. 查看服务器统计");
            System.out.println("8. 数据备份");
            System.out.println("0. 注销");
        } else {
            // 普通用户菜单
            System.out.println("\n=== 欢迎来到商城（用户模式）===");
            System.out.println("当前用户: " + username + " (普通用户)");
            System.out.println("1. 浏览所有商品");
            System.out.println("2. 自定义排序浏览商品");
            System.out.println("3. 添加商品到购物车");
            System.out.println("4. 查看购物车");
            System.out.println("5. 结账");
            System.out.println("6. 查看订单历史");
            System.out.println("0. 注销");
        }
    }



    /**
     * 处理用户菜单选择
     */
    private void handleUserMenu(int choice) {
        if ("admin".equals(currentUserRole)) {
            // 管理员菜单处理
            switch (choice) {
                case 1:
                    browseProducts(null);
                    break;
                case 2:
                    addProduct();
                    break;
                case 3:
                    updateProduct();
                    break;
                case 4:
                    deleteProduct();
                    break;
                case 5:
                    viewAllUsers();
                    break;
                case 6:
                    deleteUser();
                    break;
                case 7:
                    viewServerStats();
                    break;
                case 8:
                    backupData();
                    break;
                case 0:
                    logout();
                    break;
                default:
                    System.out.println("无效的选项，请重新输入！");
            }
        } else {
            // 普通用户菜单处理
            switch (choice) {
                case 1:
                    browseProducts(null);
                    break;
                case 2:
                    showSortedProducts();
                    break;
                case 3:
                    addToCart();
                    break;
                case 4:
                    viewCart();
                    break;
                case 5:
                    checkout();
                    break;
                case 6:
                    viewOrderHistory();
                    break;
                case 0:
                    logout();
                    break;
                default:
                    System.out.println("无效的选项，请重新输入！");
            }
        }
    }

    /**
     * 用户注册
     */
    private void register() {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine().trim();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine().trim();
        System.out.print("请输入角色 (user/admin, 默认为user): ");
        String role = scanner.nextLine().trim();
        if (role.isEmpty()) {
            role = "user";
        }

        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

            oos.writeObject("REGISTER:" + username + ":" + password + ":" + role);
            oos.flush();

            String response = (String) ois.readObject();
            if ("REGISTER_SUCCESS".equals(response)) {
                System.out.println("注册成功！请登录。");
            } else {
                System.out.println("注册失败！用户名可能已存在。");
            }

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("注册失败: " + e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.println("关闭连接时出错: " + e.getMessage());
                }
            }
        }
    }

    /**
     * 用户登录
     */
    private void login() {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine().trim();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine().trim();

        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

            oos.writeObject("LOGIN:" + username + ":" + password);
            oos.flush();

            String response = (String) ois.readObject();
            if (response.startsWith("LOGIN_SUCCESS:")) {
                String[] parts = response.split(":");
                sessionId = parts[1];
                currentUserRole = parts[2];
                this.username = username;
                isLoggedIn = true;
                System.out.println("登录成功！欢迎，" + username + " (" +
                        (currentUserRole.equals("admin") ? "管理员" : "普通用户") + ")");

            } else {
                System.out.println("登录失败！用户名或密码错误。");
            }

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("登录失败: " + e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.println("关闭连接时出错: " + e.getMessage());
                }
            }
        }
    }


    /**
     * 用户注销
     */
    private void logout() {
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

            oos.writeObject("LOGOUT");
            oos.flush();

            String response = (String) ois.readObject();
            System.out.println("注销成功！");

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("注销时通信失败: " + e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.println("关闭连接时出错: " + e.getMessage());
                }
            }
        }

        sessionId = null;
        currentUserRole = "guest";
        isLoggedIn = false;
        username = null;
        // 不再清空本地购物车，因为数据在服务器端
        System.out.println("已成功注销！您的购物车数据已保存在服务器。");
    }

    /**
     * 浏览商品 - 通过Socket连接服务器获取数据
     * 符合任务要求：使用Socket通信而不是直接调用ProductService
     */
    private void browseProducts(Comparator<Product> comparator) {
        Socket socket = null;
        try {
            // 创建Socket连接到服务器 - 符合任务要求
            socket = new Socket(SERVER_HOST, SERVER_PORT);

            // 获取ObjectOutputStream和ObjectInputStream - 符合任务要求
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

            // 向服务器发送请求字符串 "GET_ALL_PRODUCTS" - 符合任务要求
            oos.writeObject("GET_ALL_PRODUCTS");
            oos.flush();

            // 从服务器读取响应对象，并将其强制转换为 List<Product> - 符合任务要求
            Object response = ois.readObject();
            if (response instanceof List) {
                @SuppressWarnings("unchecked")
                List<Product> products = (List<Product>) response;

                // 将获取到的商品列表打印到控制台 - 符合任务要求
                System.out.println("\n--- 商品列表 ---");
                if (products.isEmpty()) {
                    System.out.println("商店里还没有商品。");
                } else {
                    if (comparator == null) {
                        Collections.sort(products);
                    } else {
                        Collections.sort(products, comparator);
                    }
                    products.forEach(System.out::println);
                    System.out.println("共 " + products.size() + " 个商品");
                }
            } else {
                System.out.println("服务器返回数据格式错误: " + response);
            }

        } catch (IOException e) {
            System.err.println("连接服务器失败: " + e.getMessage());
            System.out.println("请确保服务器已启动在 " + SERVER_HOST + ":" + SERVER_PORT);
        } catch (ClassNotFoundException e) {
            System.err.println("数据解析失败: " + e.getMessage());
        } finally {
            // 在 finally 块中确保 Socket 被关闭 - 符合任务要求
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.println("关闭Socket时出错: " + e.getMessage());
                }
            }
        }
    }

    /**
     * 显示排序商品
     */
    private void showSortedProducts() {
        System.out.println("\n=== 选择排序方式 ===");
        System.out.println("1. 按价格从低到高");
        System.out.println("2. 按价格从高到低");
        System.out.println("3. 按库存从多到少");
        System.out.println("4. 默认排序（按ID）");
        System.out.print("请选择排序方式: ");

        String input = scanner.nextLine().trim();
        if (!input.matches("[1-4]")) {
            System.out.println("无效选择，使用默认排序。");
            browseProducts(null);
            return;
        }

        int sortChoice = Integer.parseInt(input);
        Comparator<Product> comparator = null;
        String sortDescription = "";

        switch (sortChoice) {
            case 1:
                comparator = ProductSorters.BY_PRICE_ASC;
                sortDescription = "价格从低到高";
                break;
            case 2:
                comparator = ProductSorters.BY_PRICE_DESC;
                sortDescription = "价格从高到低";
                break;
            case 3:
                comparator = ProductSorters.BY_STOCK_DESC;
                sortDescription = "库存从多到少";
                break;
            case 4:
                sortDescription = "默认排序（按ID）";
                break;
        }

        System.out.println("\n--- 商品列表（" + sortDescription + "）---");
        browseProducts(comparator);
    }

    /**
     * 添加商品到服务器端购物车 - 通过Socket通信
     */
    private boolean addToServerCart(String productId, int quantity) {
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

            // 确保sessionId正确传递
            String requestSessionId = sessionId != null ? sessionId : "";
            System.out.println("DEBUG: 发送ADD_TO_CART请求，sessionId: " + requestSessionId); // 调试信息

            oos.writeObject("ADD_TO_CART:" + productId + ":" + quantity + ":" +  requestSessionId);
            oos.flush();

            String response = (String) ois.readObject();
            if ("ADD_TO_CART_SUCCESS".equals(response)) {
                return true;
            } else if (response.startsWith("INSUFFICIENT_STOCK:")) {
                String[] parts = response.split(":");
                System.out.println("错误：库存不足！当前库存：" + parts[1]);
            } else if ("PRODUCT_NOT_FOUND".equals(response)) {
                System.out.println("错误：商品不存在！");
            } else if ("NOT_LOGGED_IN".equals(response)) {
                System.out.println("错误：请先登录！");// 如果服务器说未登录，更新客户端状态


            }
            return false;

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("添加到购物车失败: " + e.getMessage());
            return false;
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.println("关闭连接时出错: " + e.getMessage());
                }
            }
        }
    }

    /**
     * 从服务器获取购物车数据 - 通过Socket通信
     */
    private Map<String, Integer> getServerCart() {
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

            // 确保sessionId正确传递
            String requestSessionId = sessionId != null ? sessionId : "";
            System.out.println("DEBUG: 发送GET_CART请求，sessionId: " + requestSessionId); // 调试信息

            oos.writeObject("GET_CART:" + requestSessionId);
            oos.flush();

            Object response = ois.readObject();
            if (response instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Integer> cart = (Map<String, Integer>) response;
                System.out.println("DEBUG: 成功获取购物车，商品数量: " + cart.size()); // 调试信息
                return cart;
            } else if ("NOT_LOGGED_IN".equals(response)) {
                System.out.println("请先登录！");
                // 重要：这里不自动重置登录状态，让用户手动处理
                return null;
            } else {
                System.out.println("获取购物车失败: " + response);
                return new HashMap<>();
            }

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("获取购物车失败: " + e.getMessage());
            return new HashMap<>();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.println("关闭连接时出错: " + e.getMessage());
                }
            }
        }
    }

    /**
     * 根据商品ID从服务器获取商品信息 - 通过Socket通信
     */
    private Product getProductByIdFromServer(String productId) {
        // 先获取所有商品，然后查找特定的商品
        List<Product> products = getAllProductsFromServer();
        for (Product product : products) {
            if (product.getId().equals(productId)) {
                return product;
            }
        }
        return null;
    }

    /**
     * 添加商品到购物车 - 修复版本：使用服务器端购物车
     */
    private void addToCart() {
        if (!isLoggedIn) {
            System.out.println("请先登录才能添加商品到购物车！");
            return;
        }

        // 先获取商品列表，让用户知道有哪些商品
        System.out.println("正在获取商品信息...");
        List<Product> products = getAllProductsFromServer();

        if (products.isEmpty()) {
            System.out.println("暂无商品可购买！");
            return;
        }

        // 显示商品列表供用户参考
        System.out.println("\n--- 可购买商品 ---");
        products.forEach(System.out::println);

        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine().trim();

        // 通过Socket从服务器检查商品是否存在
        Product product = getProductByIdFromServer(productId);
        if (product == null) {
            System.out.println("错误：商品ID不存在！");
            return;
        }

        System.out.print("请输入购买数量: ");
        String quantityInput = scanner.nextLine().trim();

        if (!quantityInput.matches("\\d+")) {
            System.out.println("错误：请输入有效的数字！");
            return;
        }

        int quantity = Integer.parseInt(quantityInput);
        if (quantity <= 0) {
            System.out.println("错误：购买数量必须为正数！");
            return;
        }

        // 使用服务器端购物车 - 这是关键修复
        if (addToServerCart(productId, quantity)) {
            System.out.println("成功将商品 '" + product.getName() + "' 添加到购物车！");
        }
    }

    /**
     * 查看购物车 - 修复版本：使用服务器端购物车
     */
    private void viewCart() {
        if (!isLoggedIn) {
            System.out.println("请先登录才能查看购物车！");
            return;
        }

        System.out.println("\n--- 我的购物车 ---");

        // 从服务器获取购物车数据
        Map<String, Integer> serverCart = getServerCart();

        if (serverCart == null) {
            System.out.println("获取购物车数据失败！");
            return;
        }

        if (serverCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            return;
        }

        // 获取所有商品信息
        List<Product> allProducts = getAllProductsFromServer();

        double totalAmount = 0.0;
        int totalItems = 0;

        System.out.println("==================================================================================");
        System.out.printf("%-8s | %-20s | %-10s | %-6s | %-8s | %-10s\n",
                "商品ID", "商品名称", "单价", "数量", "小计", "库存状态");
        System.out.println("==================================================================================");

        for (Map.Entry<String, Integer> entry : serverCart.entrySet()) {
            String productId = entry.getKey();
            int quantity = entry.getValue();

            Product product = getProductByIdFromServer(productId);
            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                totalAmount += subtotal;
                totalItems += quantity;

                String stockStatus = quantity <= product.getStock() ? "库存充足" : "库存不足";

                System.out.printf("%-8s | %-20s | ¥%-9.2f | %-6d | ¥%-7.2f | %-10s\n",
                        product.getId(),
                        product.getName(),
                        product.getPrice(),
                        quantity,
                        subtotal,
                        stockStatus);
            } else {
                System.out.printf("%-8s | %-20s | %-10s | %-6d | %-8s | %-10s\n",
                        productId, "商品不存在", "N/A", quantity, "N/A", "N/A");
            }
        }

        System.out.println("==================================================================================");
        System.out.printf("总计: %d 种商品, %d 件商品, 总金额: ¥%.2f\n",
                serverCart.size(), totalItems, totalAmount);
        System.out.println("==================================================================================");
    }



    /**
     * 结账 - 修复版本：使用服务器端购物车
     */
    private void checkout() {
        if (!isLoggedIn) {
            System.out.println("请先登录才能结账！");
            return;
        }

        // 先显示购物车内容
        viewCart();

        Map<String, Integer> serverCart = getServerCart();
        if (serverCart == null || serverCart.isEmpty()) {
            System.out.println("购物车为空，无法结账");
            return;
        }

        System.out.print("确认结账吗？(y/n): ");
        String confirm = scanner.nextLine().trim().toLowerCase();

        if ("y".equals(confirm) || "yes".equals(confirm)) {
            // 调用服务器端结账
            Socket socket = null;
            try {
                socket = new Socket(SERVER_HOST, SERVER_PORT);
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

                // 确保sessionId正确传递
                String requestSessionId = sessionId != null ? sessionId : "";
                System.out.println("DEBUG: 发送CHECKOUT请求，sessionId: " + requestSessionId);

                oos.writeObject("CHECKOUT:" +requestSessionId);
                oos.flush();

                String response = (String) ois.readObject();
                System.out.println("DEBUG: 服务器结账响应: " + response);
                if ("CHECKOUT_SUCCESS".equals(response)) {
                    System.out.println("结账成功! 感谢您的购买！");
                    System.out.println("订单已完成，购物车已清空！");
                } else if ("CART_EMPTY".equals(response)) {
                    System.out.println("结账失败：购物车为空！");
                } else {
                    System.out.println("结账失败: " + response);
                }

            } catch (IOException | ClassNotFoundException e) {
                System.err.println("结账失败: " + e.getMessage());
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.err.println("关闭连接时出错: " + e.getMessage());
                    }
                }
            }
        } else {
            System.out.println("已取消结账。");
        }
    }

    /**
     * 数据备份
     */
    private void backupData() {

        if (!isLoggedIn || !"admin".equals(currentUserRole)) {
            System.out.println("权限不足！");
            System.out.println("DEBUG: isLoggedIn=" + isLoggedIn + ", currentUserRole=" + currentUserRole);
            return;
        }

        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

            oos.writeObject("BACKUP_DATA:"+ sessionId);
            oos.flush();

            Object response = ois.readObject();
            System.out.println("\n=== 数据备份功能 ===");
            System.out.println("服务器响应: " + response);

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("备份失败: " + e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.println("关闭连接时出错: " + e.getMessage());
                }
            }
        }
    }

    /**
     * 退出程序
     */
    private void exit() {
        if (isLoggedIn) {
            logout();
        }

        System.out.println("\n感谢使用商城系统，再见！");
        System.exit(0);
    }

    /**
     * 获取所有商品列表 - 通过Socket通信
     */
    private List<Product> getAllProductsFromServer() {
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

            oos.writeObject("GET_ALL_PRODUCTS");
            oos.flush();

            Object response = ois.readObject();
            if (response instanceof List) {
                @SuppressWarnings("unchecked")
                List<Product> products = (List<Product>) response;
                return products;
            }
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("获取商品数据失败: " + e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.println("关闭Socket时出错: " + e.getMessage());
                }
            }
        }
        return Collections.emptyList();
    }


    /**
     * 查看所有用户（管理员功能）
     */
    private void viewAllUsers() {
        // 添加管理员权限验证
        if (!isLoggedIn || !"admin".equals(currentUserRole)) {
            System.out.println("权限不足！只有管理员可以查看用户列表。");
            return;
        }
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

            // 修复：传递sessionId给服务器
            String requestSessionId = sessionId != null ? sessionId : "";
            System.out.println("DEBUG: 发送GET_ALL_USERS_INFO请求，sessionId: " + requestSessionId);

            oos.writeObject("GET_ALL_USERS_INFO:"+ requestSessionId);
            oos.flush();

            Object response = ois.readObject();
            if (response instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, User> users = (Map<String, User>) response;

                System.out.println("\n=== 所有用户列表 ===");
                System.out.println("================================================");
                System.out.printf("%-15s %-10s %-20s %-10s\n",
                        "用户名", "角色", "注册时间", "登录状态");
                System.out.println("================================================");

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                for (User user : users.values()) {
                    String regTime = sdf.format(new Date(user.getRegistrationTime()));
                    String loginStatus = user.isLoggedIn() ? "已登录" : "未登录";

                    System.out.printf("%-15s %-10s %-20s %-10s\n",
                            user.getUsername(),
                            user.getRole(),
                            regTime,
                            loginStatus);
                }
                System.out.println("================================================");
                System.out.println("总计: " + users.size() + " 个用户");

                // 统计信息
                long adminCount = users.values().stream()
                        .filter(user -> "admin".equals(user.getRole()))
                        .count();
                long userCount = users.values().stream()
                        .filter(user -> "user".equals(user.getRole()))
                        .count();
                long onlineCount = users.values().stream()
                        .filter(User::isLoggedIn)
                        .count();

                System.out.println("管理员: " + adminCount + " 人");
                System.out.println("普通用户: " + userCount + " 人");
                System.out.println("在线用户: " + onlineCount + " 人");

            } else if ("PERMISSION_DENIED".equals(response)) {
                System.out.println("权限不足！只有管理员可以查看用户列表。");
            } else {
                System.out.println("获取用户列表失败: " + response);
            }

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("获取用户列表失败: " + e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.println("关闭连接时出错: " + e.getMessage());
                }
            }
        }
    }

    /**
     * 删除用户（管理员功能）
     */
    private void deleteUser() {
        // 添加管理员权限验证
        if (!isLoggedIn || !"admin".equals(currentUserRole)) {
            System.out.println("权限不足！只有管理员可以删除用户。");
            return;
        }
        System.out.println("\n=== 删除用户 ===");

        // 先显示所有用户
        viewAllUsers();

        System.out.print("\n请输入要删除的用户名: ");
        String usernameToDelete = scanner.nextLine().trim();

        // 防止管理员删除自己
        if (usernameToDelete.equals(this.username)) {
            System.out.println("错误：不能删除当前登录的用户！");
            return;
        }

        System.out.print("确认删除用户 '" + usernameToDelete + "' 吗？此操作不可恢复！(y/n): ");
        String confirm = scanner.nextLine().trim().toLowerCase();

        if ("y".equals(confirm) || "yes".equals(confirm)) {
            Socket socket = null;
            try {
                socket = new Socket(SERVER_HOST, SERVER_PORT);
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

                // 修复：在DELETE_USER请求中也传递sessionId
                String requestSessionId = sessionId != null ? sessionId : "";
                System.out.println("DEBUG: 发送DELETE_USER请求，sessionId: " + requestSessionId);

                oos.writeObject("DELETE_USER:" + usernameToDelete+":"+ requestSessionId);
                oos.flush();

                String response = (String) ois.readObject();
                if ("DELETE_USER_SUCCESS".equals(response)) {
                    System.out.println("用户删除成功！");
                } else if ("DELETE_USER_FAILED".equals(response)) {
                    System.out.println("用户删除失败，用户可能不存在！");
                } else if ("PERMISSION_DENIED".equals(response)) {
                    System.out.println("权限不足！");
                } else if ("NOT_LOGGED_IN".equals(response)) {
                    System.out.println("删除失败：用户未登录！");
                } else if ("CANNOT_DELETE_SELF".equals(response)) {
                    System.out.println("错误：不能删除当前登录的用户！");
                }
                else {
                    System.out.println("删除失败: " + response);
                }

            } catch (IOException | ClassNotFoundException e) {
                System.err.println("删除用户失败: " + e.getMessage());
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.err.println("关闭连接时出错: " + e.getMessage());
                    }
                }
            }
        } else {
            System.out.println("已取消删除操作。");
        }
    }

    /**
     * 添加新商品（管理员功能）
     */
    private void addProduct() {
        if (!isLoggedIn || !"admin".equals(currentUserRole)) {
            System.out.println("权限不足！只有管理员可以添加商品。");
            return;
        }

        System.out.println("\n--- 添加新商品 ---");

        System.out.print("请输入商品ID: ");
        String id = scanner.nextLine().trim();

        System.out.print("请输入商品名称: ");
        String name = scanner.nextLine().trim();

        System.out.print("请输入商品价格: ");
        String priceInput = scanner.nextLine().trim();

        System.out.print("请输入商品库存: ");
        String stockInput = scanner.nextLine().trim();

        // 输入验证
        if (id.isEmpty() || name.isEmpty()) {
            System.out.println("错误：商品ID和名称不能为空！");
            return;
        }

        double price;
        int stock;

        try {
            price = Double.parseDouble(priceInput);
            stock = Integer.parseInt(stockInput);

            if (price < 0 || stock < 0) {
                System.out.println("错误：价格和库存不能为负数！");
                return;
            }
        } catch (NumberFormatException e) {
            System.out.println("错误：请输入有效的数字！");
            return;
        }

        // 发送添加商品请求到服务器
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

            String requestSessionId = sessionId != null ? sessionId : "";
            oos.writeObject("ADD_PRODUCT:" + id + ":" + name + ":" + price + ":" + stock + ":" + requestSessionId);
            oos.flush();

            String response = (String) ois.readObject();
            if ("ADD_PRODUCT_SUCCESS".equals(response)) {
                System.out.println("商品添加成功！");
            } else if ("PRODUCT_ID_EXISTS".equals(response)) {
                System.out.println("错误：商品ID已存在！");
            } else if ("PERMISSION_DENIED".equals(response)) {
                System.out.println("权限不足！");
            } else {
                System.out.println("添加商品失败: " + response);
            }

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("添加商品失败: " + e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.println("关闭连接时出错: " + e.getMessage());
                }
            }
        }
    }

    /**
     * 修改商品信息（管理员功能）
     */
    private void updateProduct() {
        if (!isLoggedIn || !"admin".equals(currentUserRole)) {
            System.out.println("权限不足！只有管理员可以修改商品。");
            return;
        }

        System.out.println("\n--- 修改商品信息 ---");

        // 先显示所有商品
        browseProducts(null);

        System.out.print("请输入要修改的商品ID: ");
        String productId = scanner.nextLine().trim();

        // 获取当前商品信息
        Product product = getProductByIdFromServer(productId);
        if (product == null) {
            System.out.println("错误：商品不存在！");
            return;
        }

        System.out.println("当前商品信息:");
        System.out.println("ID: " + product.getId());
        System.out.println("名称: " + product.getName());
        System.out.println("价格: " + product.getPrice());
        System.out.println("库存: " + product.getStock());
        System.out.println();

        System.out.print("请输入新商品名称 (直接回车保持原值): ");
        String newName = scanner.nextLine().trim();
        if (newName.isEmpty()) {
            newName = product.getName();
        }

        System.out.print("请输入新价格 (直接回车保持原值): ");
        String priceInput = scanner.nextLine().trim();
        double newPrice = product.getPrice();
        if (!priceInput.isEmpty()) {
            try {
                newPrice = Double.parseDouble(priceInput);
                if (newPrice < 0) {
                    System.out.println("错误：价格不能为负数！");
                    return;
                }
            } catch (NumberFormatException e) {
                System.out.println("错误：请输入有效的价格！");
                return;
            }
        }

        System.out.print("请输入新库存 (直接回车保持原值): ");
        String stockInput = scanner.nextLine().trim();
        int newStock = product.getStock();
        if (!stockInput.isEmpty()) {
            try {
                newStock = Integer.parseInt(stockInput);
                if (newStock < 0) {
                    System.out.println("错误：库存不能为负数！");
                    return;
                }
            } catch (NumberFormatException e) {
                System.out.println("错误：请输入有效的库存！");
                return;
            }
        }

        // 发送修改商品请求到服务器
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

            String requestSessionId = sessionId != null ? sessionId : "";
            oos.writeObject("UPDATE_PRODUCT:" + productId + ":" + newName + ":" + newPrice + ":" + newStock + ":" + requestSessionId);
            oos.flush();

            String response = (String) ois.readObject();
            if ("UPDATE_PRODUCT_SUCCESS".equals(response)) {
                System.out.println("商品修改成功！");
            } else if ("PRODUCT_NOT_FOUND".equals(response)) {
                System.out.println("错误：商品不存在！");
            } else if ("PERMISSION_DENIED".equals(response)) {
                System.out.println("权限不足！");
            } else {
                System.out.println("修改商品失败: " + response);
            }

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("修改商品失败: " + e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.println("关闭连接时出错: " + e.getMessage());
                }
            }
        }
    }

    /**
     * 删除商品（管理员功能）
     */
    private void deleteProduct() {
        if (!isLoggedIn || !"admin".equals(currentUserRole)) {
            System.out.println("权限不足！只有管理员可以删除商品。");
            return;
        }

        System.out.println("\n--- 删除商品 ---");

        // 先显示所有商品
        browseProducts(null);

        System.out.print("请输入要删除的商品ID: ");
        String productId = scanner.nextLine().trim();

        // 获取商品信息用于确认
        Product product = getProductByIdFromServer(productId);
        if (product == null) {
            System.out.println("错误：商品不存在！");
            return;
        }

        System.out.println("您要删除的商品信息:");
        System.out.println("ID: " + product.getId());
        System.out.println("名称: " + product.getName());
        System.out.println("价格: " + product.getPrice());
        System.out.println("库存: " + product.getStock());

        System.out.print("确认删除这个商品吗？此操作不可恢复！(y/n): ");
        String confirm = scanner.nextLine().trim().toLowerCase();

        if (!"y".equals(confirm) && !"yes".equals(confirm)) {
            System.out.println("已取消删除操作。");
            return;
        }

        // 发送删除商品请求到服务器
        Socket socket = null;
        try {
            socket = new Socket(SERVER_HOST, SERVER_PORT);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

            String requestSessionId = sessionId != null ? sessionId : "";
            oos.writeObject("DELETE_PRODUCT:" + productId + ":" + requestSessionId);
            oos.flush();

            String response = (String) ois.readObject();
            if ("DELETE_PRODUCT_SUCCESS".equals(response)) {
                System.out.println("商品删除成功！");
            } else if ("PRODUCT_NOT_FOUND".equals(response)) {
                System.out.println("错误：商品不存在！");
            } else if ("PERMISSION_DENIED".equals(response)) {
                System.out.println("权限不足！");
            } else {
                System.out.println("删除商品失败: " + response);
            }

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("删除商品失败: " + e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.println("关闭连接时出错: " + e.getMessage());
                }
            }
        }
    }

    /**
     * 查看服务器统计（管理员功能）
     */
    private void viewServerStats() {
        System.out.println("\n--- 查看服务器统计 ---");
        System.out.println("功能开发中...");
    }

    /**
     * 查看订单历史（用户功能）
     */
    private void viewOrderHistory() {
        System.out.println("\n--- 查看订单历史 ---");
        System.out.println("功能开发中...");
    }



    public static void main(String[] args) {
        new EStoreClient().start();
    }
}